package com.me.study.concurrent.线程通信;

import com.me.common.util.SleepUtil;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试 Condition：<p>
 *  1，调用 await() 之前必须获得锁，否则报错 IllegalMonitorStateException；<p>
 *  2，调用 await() 之后会释放锁，并等待唤醒； <p>
 *
 * @author ME
 * @date   2019/3/6 11:43
 */
public class TestCondition {

    private static Lock lock;
    private static Condition condition;

    @Before
    public void before() {
        lock = new ReentrantLock();
        condition = lock.newCondition();
    }

    /**
     * 超时等待时：先超时，再唤醒，不会报错，空唤醒
     */
    @Test
    public void timeAwaitAndSignal() {
        new Thread(() -> {
            lock.lock();
            try {
                // 调用 await() 之前必须获得锁，否则报错 IllegalMonitorStateException
                boolean isSignal = condition.await(1, TimeUnit.SECONDS);
                // 调用 await() 之后会释放锁，并等待唤醒
                if (isSignal) {
                    System.out.println(Thread.currentThread().getName() + " 被主动唤醒了");
                } else {
                    System.out.println(Thread.currentThread().getName() + " 被超时唤醒了");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "thread-time-await").start();

        SleepUtil.ms(1100);
        lock.lock();
        try {
            condition.signal();
        } finally {
            lock.unlock();
        }
        System.out.println("await() 先超时，再唤醒");
    }

    @Test
    public void awaitAndSignal() {
        System.out.println("先准备 10个 等待的线程");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    // 调用 await() 之前必须获得锁，否则报错 IllegalMonitorStateException
                    condition.await();
                    // 调用 await() 之后会释放锁，并等待唤醒
                    SleepUtil.ms(300);
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }, "thread" + (i + 1)).start();
        }

        SleepUtil.ms(200);
        lock.lock();
        try {
            condition.signalAll();
        } finally {
            lock.unlock();
        }
        SleepUtil.seconds(4);
    }

}
